<template>
  <div class="photo-container">
    <el-row :gutter="20">
      <!-- 左侧上传区域 -->
      <el-col :span="8">
        <el-card class="upload-card">
          <template #header>
            <div class="card-header">
              <span>上传照片</span>
              <el-button type="primary" @click="handleUpload">选择照片</el-button>
            </div>
          </template>
          <div class="upload-area">
            <el-upload
              ref="uploadRef"
              class="upload-box"
              drag
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept="image/*"
            >
              <template #default>
                <div v-if="!currentImage" class="upload-content">
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    拖拽文件到此处或 <em>点击上传</em>
                  </div>
                </div>
                <div v-else class="preview-box">
                  <img :src="previewUrl" class="upload-preview" />
                </div>
              </template>
            </el-upload>
          </div>
        </el-card>
      </el-col>
      
      <!-- 中间预览区域 -->
      <el-col :span="8">
        <el-card class="preview-card">
          <template #header>
            <div class="card-header">
              <span>预览</span>
              <div class="preview-actions" v-if="currentImage">
                <el-button type="primary" @click="handleSave" :disabled="!isCropped">保存</el-button>
                <el-button @click="handleReset">重置</el-button>
              </div>
            </div>
          </template>
          <div class="preview-area">
            <div v-if="currentImage" class="image-container">
              <VueCropper
                ref="cropperRef"
                :src="previewUrl"
                :aspect-ratio="cropperAspectRatio"
                :view-mode="2"
                :guides="true"
                :center="true"
                :highlight="true"
                :background="false"
                :auto-crop="true"
                :auto-crop-area="0.8"
                :movable="true"
                :rotatable="true"
                :scalable="true"
                :zoomable="true"
                @crop="onCrop"
                @ready="onCropperReady"
              />
            </div>
            <el-empty v-else description="请上传照片"></el-empty>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧控制面板 -->
      <el-col :span="8">
        <el-card class="control-card">
          <template #header>
            <div class="card-header">
              <span>调整选项</span>
            </div>
          </template>
          
          <el-tabs v-model="activeTab">
            <!-- 裁剪选项 -->
            <el-tab-pane label="裁剪" name="crop">
              <div class="control-item">
                <span class="label">证件照尺寸</span>
                <el-select v-model="idPhotoOptions.size" placeholder="选择尺寸" @change="updateCropperAspectRatio">
                  <el-option
                    v-for="(size, key) in photoSizes"
                    :key="key"
                    :label="size.label"
                    :value="key"
                  />
                </el-select>
              </div>
              <div class="control-item">
                <span class="label">缩放</span>
                <el-slider v-model="cropperScale" :min="50" :max="200" :step="1" @input="updateCropperScale" />
              </div>
              <div class="control-item">
                <span class="label">旋转</span>
                <el-slider v-model="cropperRotate" :min="-180" :max="180" :step="1" @input="updateCropperRotate" />
              </div>
            </el-tab-pane>

            <!-- 美化选项 -->
            <el-tab-pane label="美化" name="beautify">
              <div class="control-item">
                <span class="label">亮度</span>
                <el-slider v-model="options.brightness" :min="0" :max="200" :step="1" />
              </div>
              <div class="control-item">
                <span class="label">对比度</span>
                <el-slider v-model="options.contrast" :min="0" :max="200" :step="1" />
              </div>
              <div class="control-item">
                <span class="label">饱和度</span>
                <el-slider v-model="options.saturation" :min="0" :max="200" :step="1" />
              </div>
              <div class="control-item">
                <span class="label">锐化</span>
                <el-slider v-model="options.sharpen" :min="0" :max="100" :step="1" />
              </div>
            </el-tab-pane>
            
            <!-- 证件照选项 -->
            <el-tab-pane label="证件照" name="idphoto">
              <div class="control-item">
                <span class="label">背景颜色</span>
                <el-radio-group v-model="idPhotoOptions.background">
                  <el-radio label="white">白色</el-radio>
                  <el-radio label="blue">蓝色</el-radio>
                  <el-radio label="red">红色</el-radio>
                </el-radio-group>
              </div>
              <div class="control-item">
                <span class="label">智能优化</span>
                <el-switch v-model="idPhotoOptions.enhance" />
              </div>
              <div class="control-item">
                <span class="label">美颜</span>
                <el-switch v-model="idPhotoOptions.beautify" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import VueCropper from 'vue-cropperjs'
import 'cropperjs/dist/cropper.css'
import { getPhotoSizes, processIdPhoto, exportPrintFile } from '@/api/photo'

// 照片尺寸配置
const photoSizes = ref({})

// 状态变量
const uploadRef = ref(null)
const cropperRef = ref(null)
const currentImage = ref(null)
const previewUrl = ref('')
const activeTab = ref('crop')
const detecting = ref(false)
const isCropped = ref(false)
const cropperScale = ref(100)
const cropperRotate = ref(0)
const cropData = ref(null)

// 美化选项
const options = ref({
  brightness: 100,
  contrast: 100,
  saturation: 100,
  sharpen: 0
})

// 证件照选项
const idPhotoOptions = ref({
  size: '1inch',
  background: 'white',
  enhance: true,
  beautify: false
})

// 计算裁剪比例
const cropperAspectRatio = computed(() => {
  const size = photoSizes.value[idPhotoOptions.value.size]
  return size ? size.width / size.height : 1
})

// 初始化
onMounted(async () => {
  try {
    photoSizes.value = await getPhotoSizes()
  } catch (error) {
    console.error('获取照片尺寸失败:', error)
    ElMessage.error('获取照片尺寸失败')
  }
})

// 处理文件选择
async function handleFileChange(file) {
  if (!file) return
  
  try {
    // 读取文件
    const reader = new FileReader()
    reader.onload = async (e) => {
      currentImage.value = file.raw
      previewUrl.value = e.target.result
      isCropped.value = false
      
      // 等待DOM更新
      await nextTick()
      
      // 重置裁剪器
      if (cropperRef.value) {
        cropperRef.value.replace(e.target.result)
      }
    }
    reader.readAsDataURL(file.raw)
  } catch (error) {
    console.error('读取文件错误:', error)
    ElMessage.error('读取文件失败')
  }
}

// 裁剪器准备就绪
function onCropperReady() {
  // 设置初始裁剪比例
  updateCropperAspectRatio()
}

// 更新裁剪器缩放
function updateCropperScale(value) {
  if (cropperRef.value) {
    const scale = value / 100
    cropperRef.value.zoomTo(scale)
  }
}

// 更新裁剪器旋转
function updateCropperRotate(value) {
  if (cropperRef.value) {
    cropperRef.value.rotateTo(value)
  }
}

// 更新裁剪比例
function updateCropperAspectRatio() {
  if (cropperRef.value) {
    cropperRef.value.setAspectRatio(cropperAspectRatio.value)
  }
}

// 裁剪回调
function onCrop(data) {
  cropData.value = data
  isCropped.value = true
}

// 触发上传
function handleUpload() {
  uploadRef.value.handleClick()
}

// 保存图片
async function handleSave() {
  if (!currentImage.value || !cropData.value) return
  
  try {
    // 获取裁剪后的图片数据
    const canvas = cropperRef.value.getCroppedCanvas()
    
    // 将 Canvas 转换为 Blob
    const blob = await new Promise(resolve => {
      canvas.toBlob(resolve, 'image/jpeg', 0.95)
    })
    
    // 创建文件对象
    const file = new File([blob], 'cropped.jpg', { type: 'image/jpeg' })
    
    // 准备处理选项
    const options = []
    if (idPhotoOptions.value.beautify) {
      options.push('whitening', 'removeWrinkle', 'removeAcne')
    }
    if (idPhotoOptions.value.enhance) {
      options.push('faceLift')
    }

    // 创建 FormData
    const formData = new FormData()
    formData.append('file', file)
    formData.append('size', idPhotoOptions.value.size)
    formData.append('background', idPhotoOptions.value.background)
    if (options.length > 0) {
      options.forEach(option => {
        formData.append('options', option)
      })
    }

    // 调用后端 API 处理图片
    const response = await processIdPhoto(formData)

    if (response.code === 0) {
      ElMessage.success('处理成功')
      
      // 下载处理后的图片
      const link = document.createElement('a')
      link.href = response.data
      link.download = `证件照_${photoSizes.value[idPhotoOptions.value.size].label}_${new Date().getTime()}.jpg`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      throw new Error(response.msg || '处理失败')
    }
    
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败')
  }
}

// 重置设置
function handleReset() {
  options.value = {
    brightness: 100,
    contrast: 100,
    saturation: 100,
    sharpen: 0
  }
  
  idPhotoOptions.value = {
    size: '1inch',
    background: 'white',
    enhance: true,
    beautify: false
  }

  cropperScale.value = 100
  cropperRotate.value = 0
  
  if (cropperRef.value) {
    cropperRef.value.reset()
  }
}
</script>

<style scoped>
.photo-container {
  padding: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-card,
.preview-card,
.control-card {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
}

.upload-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.upload-box {
  width: 100%;
  height: 100%;
}

:deep(.el-upload) {
  width: 100%;
  height: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-content {
  text-align: center;
}

.preview-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-preview {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.preview-area {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.image-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.control-item {
  margin-bottom: 20px;
}

.control-item .label {
  display: block;
  margin-bottom: 8px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
  height: calc(100% - 55px);
  overflow-y: auto;
}

:deep(.cropper-container) {
  max-width: 100%;
  max-height: 100%;
}

:deep(.cropper-wrap-box),
:deep(.cropper-canvas),
:deep(.cropper-drag-box),
:deep(.cropper-crop-box),
:deep(.cropper-face) {
  max-width: 100%;
  max-height: 100%;
}
</style> 